<template>
  <div style="padding: 10px 0">
    <el-button type="success" @click="router.push('/home/user/edit')">添加</el-button>
  </div>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column fixed prop="id" label="ID" width="180"/>
    <el-table-column prop="username" label="账号" width="180"/>
    <el-table-column prop="nickname" label="昵称"/>
    <el-table-column prop="password" label="密码"/>
    <el-table-column prop="phone" label="电话"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column prop="role" label="角色">
      <template #default="{row}">
        {{ row.role === 1 ? '管理员' : '用户' }}
      </template>
    </el-table-column>
    <el-table-column prop="sex" label="性别">
      <template #default="{row}">
        {{ row.sex === 1 ? '男' : '女' }}
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="{row}">
        <el-link type="primary" size="small" @click="handleEdit(row.id)">修改</el-link>
        <el-link style="margin-left: 5px" type="primary" size="small" @click="handleDel(row.id)">删除</el-link>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination background style="margin-top: 5px" layout="total, sizes, prev, pager, next, jumper" v-model:current-page="current" v-model:page-size="pageSize" :total="total"/>
</template>

<script setup name="UserView" lang="ts">
import {onMounted, ref, watch} from "vue";
import PageQuery from "@/model/PageQuery";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import UserApi from "@/axios/UserApi";
import type User from "@/model/User";

const tableData = ref<User[]>([])
const total = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)
onMounted(() => {
  loadData()
})

function loadData() {
  const pageQuery = new PageQuery();
  pageQuery.current = current.value
  pageQuery.size = pageSize.value
  UserApi.page(pageQuery)
      .then((resp) => {
        total.value = resp.data?.total || 0
        tableData.value = resp.data?.records || []
      })
}

const router = useRouter()

function handleEdit(id: number) {
  router.push("/home/user/edit?id=" + id)
}

function handleDel(id: number) {
  ElMessageBox.confirm('确认是否删除?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    UserApi.remove(id)
        .then(() => {
          ElMessage.success("删除成功")
          loadData()
        })
  })
}

watch(current, () => {
  loadData()
})

watch(pageSize, () => {
  loadData()
});


</script>


<style lang="less" scoped>
</style>